import React, { useEffect, useState } from 'react';
import {
  Input,
  Button,
  Table,
  Row,
  Col,
  Card,
  Modal,
  message,
  Form,
  Select,
  DatePicker,
  Divider,
  PageHeader,
  Space,
  TreeSelect,
  Badge,
  Avatar,
} from 'antd';
import { Redirect, connect } from 'umi';
import moment from 'moment';
import './index.less';
import { getAuthority } from '@/utils/authority';
import pagination from '@/utils/pagination';
import EditForm from './components/EditForm';
import ViewForm from './components/ViewForm';
import { getDictCode, getDictCodeLabel } from '@/utils/DataDictUtils';
import { SearchOutlined, UndoOutlined, PlusOutlined, UserOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { confirm } = Modal;
const { Option } = Select;
const ProductPage = (props) => {

  /*props中的变量是connect中接收model变量值的变量,这里的值是由model传过来的 */
  const { loading, dispatch, dataSource, classData, total } = props;
  /*存放当前选中记录 */
  const [current, setCurrent] = useState(undefined);
  const [deviceLogData, setDeviceLogData] = useState(undefined);
  /*用于刷新界面，当给refresh赋值新的日期时界面将刷新 */
  const [refresh, setRefresh] = useState(new Date().valueOf());
  /*用于控制EditForm显示弹出层 */
  const [visible, setVisible] = useState(false);
  const [viewVisible, setViewVisible] = useState(false);

  /*分页时记录当前页 */
  const [currentPage, setCurrentPage] = useState(1);
  const [treeData, setTreeData] = useState([]);
  const [alarmCount, setAlarmCount] = useState(0);
  const [alarmVisible, setAlarmVisible] = useState(false);
  /*存放当前设备状态 */
  const [deviceStatus, setDeviceStatus] = useState(undefined);
  /*设置查询条件，可以设置多个 */
  const [dataQuery, setDataQuery] = useState({
    start: 0,
    count: 20,
    sortby: '',
    isasc: 0,
    query: {
      productName: undefined,
      status: undefined,
      networkMode: undefined,
      protocol: undefined,
      newVersion:undefined,
    },
  });

  /*分页大小 */
  const [pageSize, setPageSize] = useState(20);

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      align: 'center',
      key: 'id',
      width: 80,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      align: 'center',
      key: 'productName',
    },
    {
      title: '所属协议',
      dataIndex: 'protocol',
      align: 'center',
      key: 'protocol',
      render: (_, record) => (
        <>
          {
            getDictCodeLabel('protocol', record.protocol)
          }
        </>
      )
    },
    {
      title: '连网方式',
      dataIndex: 'networkMode',
      align: 'center',
      key:'networkMode',
      render: (_, record) => (
        <>
          {
            getDictCodeLabel('networkMode', record.networkMode)
          }
        </>
      )
    },
    {
      title: '数据格式',
      dataIndex: 'dataFormat',
      align: 'center',
      key: 'dataFormat',
      render: (_, record) => (
        <>
          {
            getDictCodeLabel('dataFormat', record.dataFormat)
          }
        </>
      )
    },
    {
      title: '产品状态',
      dataIndex: 'status',
      align: 'center',
      key: 'status',
      render: (_, record) => (
        <>
          {
            getDictCodeLabel('productStatus', record.status)
          }
        </>
      )
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      render: (_, record) => (
        <>
          <a onClick={() => showViewModal(record)} >查看</a>
          <Divider type="vertical" />
          <a onClick={() => showEditModal(record)} >编辑 </a>
          <Divider type="vertical" />
          <a onClick={()=> handleStatus(record)}>{record.status===1?'停用':'启用'}</a>
          <Divider type="vertical" />
          <a onClick={()=> handleRemove(record)}>删除</a>
        </>
      ),
    }
  ];


  /*分页组件的属性设置 */
  const paginationProps = {
    ...pagination,
    total,
    pageSize,
    current: currentPage,
    onChange: page => {
      setCurrentPage(page);
      setRefresh(new Date().valueOf());
    },
    onShowSizeChange: (page, size) => {
      setCurrentPage(1);
      setPageSize(size);
      setRefresh(new Date().valueOf());
    }
  };

  /*加载完页面后执行 */
  useEffect(() => {
    /*通过dispatch调用model.js中的方法返回结果在model的list方法中进行处理的，refresh是刷新界面 */
    dataQuery.start = (currentPage - 1) * pageSize;
    dataQuery.count = pageSize;
    dispatch({
      type: 'productModel/list',
      payload: {
        params: dataQuery,
      },
    });
  }, [refresh]);


  const showViewModal =(record)=>{
    if (record) {
      dispatch({
        type: 'productModel/get',
        id: 1,
        callback: res => {
          setCurrent(res);
          setViewVisible(true);
        },
      });
    } else {
      message.warning('请选择记录');
    }
  }

  const showEditModal =(record)=>{
    if (record) {
      dispatch({
        type: 'productModel/get',
        id: 1,
        callback: res => {
          setCurrent(res);
          setVisible(true);
        },
      });
    } else {
      message.warning('请选择记录');
    }
  }

  const handleRemove =(record)=>{
    confirm({
      title: '确认要删除该产口吗?',
      width:'300px',
      onOk() {
        dispatch({ type: 'productModel/delete', productId: 1 });
      },
      onCancel() {},
    });
  }

  const handleStatus=(record)=>{
    let status = 1;
    let titleMsg = '确认要启用该产品?';
    if(record.status ===1){
      status =2;
      titleMsg = '确认要停用该产品?'
    }
    confirm({
      title: titleMsg,
      width:'300px',
      onOk() {
        dispatch({ 
          type: 'productModel/status',
          id:1,
          status:status });
      },
      onCancel() {},
    });

  }

  const onSearch = () => {
    setCurrentPage(1);
    setRefresh(new Date().valueOf());
  };

  const onReset = () => {
    setDataQuery({
      ...dataQuery,
      query: {
        productName: undefined,
        status: undefined,
        newworkMode: undefined,
        protocol: undefined,
        newVersion:undefined,
      },
    });
    onSearch();
  };

  const onAdd = () => {
    setCurrent(undefined);
    setVisible(true);
  };

  /*弹出层的取消按钮事件 */
  const handleCancel = () => {
    setVisible(false);
  };

  const handleCancelView = () => {
    setViewVisible(false);
  };

  /*弹出层的保存按钮事件 */
  const handleSubmit = (values,callback) => {
    const id = current ? current.productId : null;
    dispatch({
      type: 'productModel/submit',
      payload: {
        productId:id,
        ...values,
      },
      callback: (resp) => {
        callback(resp);
        if(resp.success){
          setCurrent(undefined);
          setVisible(false);
        }
      },
    });
  };

  const handleTableChange = (pagination, filters, sorter) => {
    setDataQuery({
      ...dataQuery,
      sortby: sorter.columnKey,
      isasc: sorter.order && sorter.order === 'descend' ? 1 : 0,
    });
    setRefresh(new Date().valueOf());
  };

  const statusOptions = getDictCode('productStatus').map(d => (
    <Option key={d.codeValue}>{d.codeLabel}</Option>
  ));

  const networkModeOptions = getDictCode('networkMode').map(d => (
    <Option key={d.codeValue}>{d.codeLabel}</Option>
  ));

  const protocolOptions = getDictCode('protocol').map(d => (
    <Option key={d.codeValue}>{d.codeLabel}</Option>
  ));

  const yesNoOptions = getDictCode('yesNo').map(d => (
    <Option key={d.codeValue}>{d.codeLabel}</Option>
  ));

return (
    <div className="page">
      <Row >
        <Col span='20'>
          <PageHeader title="产品列表" />
        </Col>
      </Row>
      <Divider style={{ margin: 0 }} />
      <Card
        bordered={false}
        bodyStyle={{
          padding: '10px 10px 10px 10px',
        }}
      >
        <Row className="row">
          <Form layout="inline" style={{ width: '100%' }}>
            <Col span={20}>
              <Row>
                <Col span={8}><Form.Item label='产品名称:'>
                  <Input
                    allowClear
                    maxLength={50}
                    placeholder='请输入产品名称'
                    onChange={e => {
                      setDataQuery({
                        ...dataQuery,
                        query: {
                          ...dataQuery.query,
                          productName: e.target.value,
                        },
                      });
                    }}
                    value={dataQuery.query.productName}

                  />
                </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label='联网方式:'>
                    <Select
                      value={dataQuery.query.networkMode === '' ? undefined : dataQuery.query.networkMode}
                      allowClear
                      placeholder='请选择联网方式'
                      style={{ width: 150 }}
                      onChange={value => {
                        setDataQuery({
                          ...dataQuery,
                          query: {
                            ...dataQuery.query,
                            networkMode: value || undefined,
                          },
                        });
                      }}
                    >
                      {networkModeOptions}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label='是否有新版本:'>
                    <Select
                      value={dataQuery.query.newVersion === '' ? undefined : dataQuery.query.newVersion}
                      allowClear
                      placeholder='请选择是否有新版本'
                      style={{ width: 150 }}
                      onChange={value => {
                        setDataQuery({
                          ...dataQuery,
                          query: {
                            ...dataQuery.query,
                            newVersion: value || '',
                          },
                        });
                      }}
                    >
                      {yesNoOptions}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row style={{ marginTop: '5px' }}>
                <Col span={8}>
                  <Form.Item label='所属协议:'>
                  <Select
                      value={dataQuery.query.protocol === '' ? undefined : dataQuery.query.protocol}
                      allowClear
                      placeholder='请选择所属协议'
                      style={{ width: 150 }}
                      onChange={value => {
                        setDataQuery({
                          ...dataQuery,
                          query: {
                            ...dataQuery.query,
                            protocol: value || '',
                          },
                        });
                      }}
                    >
                      {protocolOptions}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label='产品状态:'>
                    <Select
                      value={dataQuery.query.status === '' ? undefined : dataQuery.query.status}
                      allowClear
                      placeholder='请选择状态'
                      style={{ width: 150 }}
                      onChange={value => {
                        setDataQuery({
                          ...dataQuery,
                          query: {
                            ...dataQuery.query,
                            status: value || '',
                          },
                        });
                      }}
                    >
                      {statusOptions}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </Col>
            <Col >
              <Form.Item style={{ float: 'right' }}>
                <Space direction='vertical' >
                  <Button type="primary" icon={<SearchOutlined />} className="ml10" onClick={onSearch}>
                    查询
                </Button>
                  <Button type="default" icon={<UndoOutlined />} className="ml10" onClick={onReset}>
                    重置
                </Button>
                  {/* <Button  type='default' className="ml10" >批量升级 </Button> */}
                </Space>
              </Form.Item>
            </Col>
          </Form>
        </Row>
      </Card>
      <Card
        bordered={false}
        style={{
          marginTop: 10,
        }}
        bodyStyle={{
          padding: '0px 10px 10px 10px',
        }}
      >
        <Table
          size="middle"
          rowKey="id"
          loading={loading}
          columns={columns}
          bordered
          pagination={paginationProps}
          dataSource={dataSource}
          onChange={handleTableChange}
        />
      </Card>
      {/*设置弹出层并将属性传递过去 */}
      <EditForm
        current={current}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
        dispatch={dispatch}
      />
      <ViewForm
        dispatch={dispatch}
        current={current}
        visible={viewVisible}
        onCancel={handleCancelView}
      />
    </div>
  );
}

export default connect(({ productModel, loading }) => ({
  productModel,
  dataSource: productModel.dataSource,
  total: productModel.total,
  loading: loading.models.productModel,
}))(ProductPage);

